# coding=utf-8
import hashlib
import logging

from django.db.models import Q
from django.forms.models import model_to_dict
import json

from apps.usermanager.models import User, UserPermission, Permission
from comment.errorcode import *
from apps.demomanager import service as DemoServer
from apps.usermanager import service as UserServer
from utils.esutils import UserEs as EStools

es_tools = EStools()


def user_edit(request, params=None):
    """
    用户编辑
    :param request:
    :return:
    """
    id = params.get("id")
    name = params.get("name")
    phone = params.get("phone")
    password = params.get("password")
    email = params.get("email")
    is_admin = params.get("is_admin")
    photo = request.FILES.get("photo")
    profession = params.get("profession")
    detail = params.get("detail")
    
    if not all([id, name, phone, password, profession]):
        return ErrorMsg(PARAMS_EMPTY, "参数不全").msg
    
    # 密码加密
    md = hashlib.md5()
    md.update(('usercloud' + password + 'democloud').encode('utf-8'))
    password = md.hexdigest()
    
    user_result = UserServer.user_update(id=id, name=name, phone=phone, password=password, email=email,
                                         is_admin=is_admin, photo=photo, profession=profession, detail=detail)
    if isinstance(user_result, ErrorMsg):
        return user_result.msg
    
    keywords = params.get("keywords")
    keywords_result = []
    if keywords:
        keywords_result = UserServer.user_keywords_add(user_result, keywords.split(";"))
    if isinstance(keywords_result, ErrorMsg):
        return keywords_result.msg
    es_result = es_tools.update(user_result, keywords_result)
    return [SIGNIN_OK, "注册成功", "", 1]


def user_list(request, params=None):
    """
    查询用户
    :param request: 
    :return: 
    """
    is_admin = request.session.get("is_admin")
    if not is_admin:
        return ErrorMsg(SELECT_ERROR, "没有权限查询").msg


def user_info(request, params=None):
    """
    通过id获得用户信息
    :param request: 
    :return: 
    """
    id = params.get("user_id")
    user = User.objects.get(id=id)
    if len(user) == 0:
        return ErrorMsg(SELECT_ERROR, "未查询到此用户").msg
    else:
        return [SELECT_OK, "用户查询成功", user, 1]


def login(request, params=None):
    """
    登录
    :param request: 
    :return: 
    """
    name = params.get("username")
    users = User.objects.filter(Q(name=name) | Q(phone=name) | Q(email=name))
    if users.count() == 0:
        return ErrorMsg(LOGIN_EMPTY, "用户名或密码错误").msg
    
    password = params.get("password")
    # 密码加密
    md = hashlib.md5()
    md.update(('usercloud' + password + 'democloud').encode('utf-8'))
    password = md.hexdigest()
    for user in users:
        if user.password == password:
            request.session["login"] = True
            request.session["user_id"] = user.id
            request.session["user_name"] = user.name
            request.session["is_admin"] = user.is_admin
            request.session["phone"] = user.phone
            # perssion_id = UserPermission.objects.filter(user_id=id).permission_id
            # perssion = Permission.objects.get(id=perssion_id).level
            # request.seesion["perssion"] = perssion
            return [LOGIN_OK, "登陆成功", '', 1]
    return ErrorMsg(LOGIN_ERROR, "用户名或密码错误").msg


def logout(request, params=None):
    """
    登出
    :param request: 
    :return: 
    """
    del request.seesion["login"]
    del request.seesion["user_id"]
    del request.seesion["user_name"]
    del request.seesion["is_admin"]
    del request.seesion["phone"]
    del request.seesion["perssion"]
    return [DELETE_OK, "登出", None, 1]


def user_base_info(request, params=None):
    """
    用户基础信息
    :param request: 
    :return: 
    """
    id = request.seesion["user_id"]
    name = request.seesion["user_name"]
    is_admin = request.seesion["is_admin"]
    phone = request.seesion["phone"]
    perssion = request.seesion["perssion"]
    result = {"id": id, "name": name, "is_admin": is_admin, "phone": phone, "perssion": perssion}
    return [SELECT_OK, "用户查询成功", result, 1]


def author_info(request, params=None):
    """
    人物信息
    :param request:
    :return:
    """
    data = {}
    user_id = params.get("user_id")
    # user_id = request.session.get("user_id")
    size = params.get("size")
    page = params.get("page")
    author_id = params.get("author_id")
    author = UserServer.user_info(author_id)
    if isinstance(author, ErrorMsg):
        return author.msg
    demos = DemoServer.demo_list_author(author_id, size, page)
    if isinstance(demos, ErrorMsg):
        return demos.msg
    follow = UserServer.is_follow(user_id, author)
    if isinstance(follow, ErrorMsg):
        return follow.msg
    key_word = UserServer.user_keywords(author)
    if isinstance(key_word, ErrorMsg):
        return key_word.msg
    download_time = UserServer.download_count(demos.get("data"))
    read_time = UserServer.read_count(demos.get("data"))
    data["author"] = {
        "author_id": author_id,
        "name": author.name,
        "photo": "\\static\\ users\\photos\\" + str(author.photo),
        "detail": author.detail,
        "phone": author.phone,
        "read_time": read_time,
        "download_time": download_time,
        "key_word": key_word,
        "write_time": demos.get("total_size")
    }
    demos["url"] = "/demomanager/demo?active=read"
    data["demos"] = demos
    data["follow"] = follow
    return [SELECT_OK, "用户查询成功", data, 1]


def sign_in(request, params=None):
    """
    注册
    :param request:
    :return:
    """
    name = params.get("name")
    phone = params.get("phone")
    password = params.get("password")
    email = params.get("email")
    is_admin = params.get("is_admin")
    photo = request.FILES.get("photo")
    profession = request.FILES.get("profession")
    detail = params.get("detail")
    
    if not all([name, phone, password]):
        return ErrorMsg(PARAMS_EMPTY, "参数不全").msg
    
    # 密码加密
    md = hashlib.md5()
    md.update(('usercloud' + password + 'democloud').encode('utf-8'))
    password = md.hexdigest()
    
    user_result = UserServer.user_add(name=name, phone=phone, password=password, email=email,
                                      is_admin=is_admin, photo=photo, profession=profession, detail=detail)
    if isinstance(user_result, ErrorMsg):
        return user_result.msg
    
    keywords = params.get("keywords")
    keywords_result = []
    if keywords:
        keywords_result = UserServer.user_keywords_add(user_result.id, keywords.split(";"))
    if isinstance(user_result, ErrorMsg):
        return user_result.msg
    es_result = es_tools.create(user_result, keywords.split(";"))
    if es_result == 0:
        keywords_result.objects.delete()
        user_result.objects.delete()
        return ERR_MSG(SIGNIN_ERROR).msg
    return [SIGNIN_OK, "注册成功", "", 1]


def user_search(request, params=None):
    """
    人物搜索
    :param request:
    :return:
    """
    # 搜索结果
    froms = params.get("froms")
    keyword = params.get("keyword")
    
    if not all([froms, keyword]):
        return ErrorMsg(PARAMS_EMPTY).msg
    
    info_list = es_tools.search(keyword, froms)
    if info_list is None:
        return ErrorMsg(SELECT_ERROR).msg
    # 加入数据表段count
    for info in info_list:
        try:
            UserServer.user_demos_num(info.get("id"))
        except Exception as e:
            info["count"] = 0
            continue
    
    return [SELECT_OK, "查询成功", info_list, 1]


def follow_user(request, params=None):
    """
    关注用户
    :param request:
    :return:
    """
    delete = params.get("delete")
    user_id = request.session.get("user_id")
    author_id = request.session.get("author_id")
    if not all([user_id, author_id]):
        return ErrorMsg(PARAMS_EMPTY).msg
    if not delete:
        result = UserServer.follow_add(user_id, author_id)
    else:
        result = UserServer.follow_del(user_id, author_id)
    if isinstance(result, ErrorMsg):
        return result.msg
    return [SELECT_OK, "查询成功", None, 1]


def user_collects(request, params=None):
    """
    用户的收藏
    :param request:
    :return:
    """
    user_id = request.session.get("user_id")
    page = params.get("page")
    size = params.get("size")
    if not all([user_id, page, size]):
        return ErrorMsg(PARAMS_EMPTY)
    result = DemoServer.collect_list(user_id, page, size)
    if isinstance(result, ErrorMsg):
        return result.msg
    return [SELECT_OK, "查询成功", result, 1]


def user_follows(request, params=None):
    """
    用户的关注
    :param request:
    :return:
    """
    user_id = request.session.get("user_id")
    page = params.get("page")
    size = params.get("size")
    if not all([user_id, page, size]):
        return ErrorMsg(PARAMS_EMPTY).msg
    result = UserServer.follow_list(user_id, page, size)
    if isinstance(result, ErrorMsg):
        return result.msg
    return [SELECT_OK, "查询成功", result, 1]
